import collections
import re
def fk_it(formula):#使用def定义一个函数
    stack = list()
    stack.append(collections.Counter())
    #append方法是向列表末端添加元素
    #一个 Counter 是一个 dict 的子类，用于计数可哈希对象。它是一个集合，元素像字典键(key)一样存储，它们的计数存储为值。计数可以是任何整数值，包括0和负数。
    found = re.findall(r'([A-Z][a-z]?)(\d*)|(\()|(\))(\d*)', formula)#函数传入的字符串，即化学方程式
    print(type(found[0]))
    print(found)
    for name, n_atom, open_paren, close_paren, coef in found:
        if name:
            stack[-1][name] += int(n_atom or 1)
        if open_paren:
            stack.append(collections.Counter())
        if close_paren:
            top = stack.pop()
            for key in top.keys():
                top[key] *= int(coef or 1)
            stack[-1] += top
    return 0
    # return dict(stack.pop())
if __name__ == '__main__':
    # list_front = '4Au+8NaCN+2H2O+O2='
    # list_behide = '4Na(Au(CN)2)+4NaOH'
    # found = re.findall(r'[A-Z][a-z]?\d*|\((?:[^()]*(?:\(.*\))?[^()]*)+\)\d+', list_front)
    # found2 =re.findall(r'[A-Z][a-z]?\d*|\((?:[^()]*(?:\(.*\))?[^()]*)+\)\d+', list_behide)
    # coef_term = re.match(r'\d+', list_front)
    # coef_term2 = re.match(r'\d+', list_behide)
    # # for i in range(len(found))
    # #     list_found3 = re.findall(r'\d',found)
    # print(found)
    # # print(found2)
    # # print(coef_term)
    # # print(coef_term2)
    # #
    print(fk_it('4Au+8NaCN+2H2O+O2'))